package debtbundler.domain.bll;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

import debtbundler.domain.entity.BalanceBook;
import debtbundler.domain.entity.BalanceSheet;
import debtbundler.domain.entity.SharedCost;

/**
 * Encapsulates the current application data and allows serializing it:
 * <ul>
 * <li>The current balance book</li>
 * <li>The current balance sheet in the book</li>
 * <li>Whether there are unsaved changes in the book</li>
 * </ul>
 * 
 * @author Anssi
 *
 */
public class CurrentData implements Serializable {
	private static final long serialVersionUID = 1L;
	
	private final BalanceBook balanceBook;
	private BalanceSheet currentSheet;
	private boolean hasUnsavedChanges;
	private Map<SharedCost, SharingMethod> sharingMethods;
	
	public CurrentData(BalanceBook book) {
		this(book, null);
	}

	public CurrentData(BalanceBook book, BalanceSheet currentSheet) {
		this.balanceBook = book;
		this.currentSheet = currentSheet;
	}

	public BalanceBook getBalanceBook() {
		return balanceBook;
	}

	public BalanceSheet getCurrentSheet() {
		return currentSheet;
	}

	public void setCurrentSheet(BalanceSheet balanceSheet) {
		this.currentSheet = balanceSheet;
	}

	public void setHasUnsavedChanges(boolean hasUnsavedChanges) {
		this.hasUnsavedChanges = hasUnsavedChanges;
	}

	public boolean hasUnsavedChanges() {
		return hasUnsavedChanges;
	}
	
	public SharingMethod getSharingMethod(SharedCost cost) {
		if (sharingMethods == null) {
			sharingMethods = new HashMap<SharedCost, SharingMethod>(); // initialize on demand to allow deserialization 
		}
		
		SharingMethod method = sharingMethods.get(cost);
		if (method == null) {
			return SharingMethod.EQUAL;
		} else {
			return method;
		}
	}

	public void setSharingMethod(SharedCost cost, SharingMethod method) {
		if (cost == null) {
			throw new NullPointerException("Null cost");
		}
		sharingMethods.put(cost, method);
	}
	
}
